package HDFSTest;

import java.util.HashMap;

import org.simgrid.msg.Host;
import org.simgrid.msg.MsgException;
import org.simgrid.msg.Process;

public class HDFSDataNode extends Process {
	private int maxNumHandler;
	private int numHandling;
	private int blockSize;
	private HashMap<String, SimFile> files;

	public HDFSDataNode(Host host, String name, String[] args) {
		super(host, name, args);
	}

	@Override
	public void main(String[] args) throws MsgException {
		this.maxNumHandler = Integer.parseInt(args[0]);
		this.blockSize = Integer.parseInt(args[1]);
		files = new HashMap<String, SimFile>();
		String[] names = args[2].split(",");
		for (int i = 0; i < names.length; i++) {
			files.put(names[i], new SimFile(names[i], (int) (Math.random() * 48) + 16, blockSize));
		}
		numHandling = 0;
	}

	public boolean respondToRequest(IORequest request) {
		String fileName = request.getFileName();
		boolean isFile = request.getData() instanceof SimFile;
		Data<?> data = request.getData();
		if (request.isWrite()) {
			if (isFile) {
				SimFile file = (SimFile) data;
				files.put(fileName, file);
			} else if (data instanceof FileBlock && files.containsKey(request.getFileName())) {
				SimFile file = files.get(request.getFileName());
				if (file.writeData((FileBlock) data)) {
					request.setComputeDuration((long) (Math.random() * 10 + 5));// TODO: memory time
					return true;
				}
			}
		} else {
			if (files.containsKey(request.getFileName())) {
				SimFile file = files.get(fileName);
				request.setData(file);
				request.setComputeDuration((long) (Math.random() * 10 + 5));// TODO: memory time
				return true;
			}
		}
		return false;
	}

}
